import request from '../../utils/config.js';
import utilApi from '../../utils/util.js';
let WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
const app = getApp()
let startTime = 60;
/* 秒级倒计时 */
function count_down(that) {
  // 渲染倒计时时钟
  that.setData({
    time: startTime
  });

  if (startTime <= 0) {
    that.setData({
      time: 0,
      inputYzmLight: false
    });
    // timeout则跳出递归
    startTime = 60;
    return;
  }
  setTimeout(function () {
    // 放在最后--
    startTime--;
    count_down(that);
  }, 1000)
}
Page({
  data: {
    animationData: {},
    telPhone: '',
    loginTypeMsg:"使用账号密码登录",
    inputYzmLight: true,
    isClickOver: false,
    loading: false,
    returnCheckNo: "",
    VerCode: '',
    avatarUrl: "",
    nickName: "",
    time: 0,
    password:"",
    pwdMobileNo:"",
    showPwdLogin:false,//密码
    hasTel: false,//验证码
    showQuickLogin:true//快速登录
  },
  onShow: function () {
    this.setData({
      avatarUrl: app.globalData.userInfo.avatarUrl,
      nickName: app.globalData.userInfo.nickName
    });
  },
  onLoad: function () {

  },

  onPullDownRefresh: function () {
      this.getUserInfoAgain();
      setTimeout(function () {
        wx.showToast({
          title: '加载成功',
          icon: 'success',
          duration: 1000
        })
        wx.stopPullDownRefresh();
      }, 1000);
  },

  //获取输入手机号值
  getTelPhone: function (e) {
    var telPhone = e.detail.value;
    this.setData({
      telPhone: e.detail.value
    })
    if (telPhone.length == 11) {
      this.setData({
        inputYzmLight: false
      })
    }else{
      this.setData({
        inputYzmLight: true
      })
    }
  },

  //获取密码输入手机号的值
  pwdPhone: function(e){
    var telPhone = e.detail.value;
    this.setData({
      pwdMobileNo: e.detail.value
    })
  },

  //登录切换
  switcher: function(e){
    console.log(e.currentTarget.dataset.flag)
    let flag = e.currentTarget.dataset.flag;
    if(flag == '1'){
      this.setData({
        showPwdLogin: false,//密码
        hasTel: false,//验证码
        showQuickLogin: true//快速登录
      });
    } else if (flag == '2'){
      if (this.data.telPhone){
        this.setData({
          inputYzmLight: false
        })
      }
      this.setData({
        showPwdLogin: false,//密码
        hasTel: true,//验证码
        showQuickLogin: false//快速登录
      });
    } else if (flag == '3') {
      this.setData({
        showPwdLogin: true,//密码
        hasTel: false,//验证码
        showQuickLogin: false//快速登录
      });
    }
  },

  //获取密码值
  pwdSave: function(e){
    var pwd = e.detail.value;
    this.setData({
      password: e.detail.value
    })
  },

  getVerCode: function (e) {
    this.setData({
      VerCode: e.detail.value
    })
  },

  //点击获取验证码 
  yzTel: function () {
    if (!this.data.telPhone) {
      this.showErrorMsg("请输入手机号");
      return;
    }
    this.setData({
      inputYzmLight: true
    });
    count_down(this);
    wx.showLoading({
      title: '加载中',
    });

    let _that = this;
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: "",
    }
    let bodyInfo = {
      mobileNo: this.data.telPhone,
      smsKind: "checkNo"
    }
    request.requestLogin_api("sendCheckNo", headerInfo, bodyInfo, (obj) => {
      wx.hideLoading();
      console.log("获取验证码成功=", obj)
      if (obj.data.isSuccess == 'T') {
        //保存数据
        let body = obj.data.body;
        _that.setData({
          returnCheckNo: body
        });
      }
    }, (obj) => {
      wx.hideLoading();
      console.log("获取验证码失败=", obj)
    })

  },
  // 点击登录
  submit: function () {
    if (this.data.showPwdLogin){
      this.passwordFun();
    } else if (this.data.hasTel){
      this.yanZcodeFun();
    }
  },

  //密码登录
  passwordFun: function(){
    var telPhone = this.data.pwdMobileNo;
    var password = this.data.password;
    if (!telPhone) {
      this.showErrorMsg("请输入手机号");
      return
    } else if (!utilApi.isValidNo(telPhone)){
      this.showErrorMsg("手机号格式不正确");
      return
    } else if (!this.data.password) {
      if (!password) {
        this.showErrorMsg("请输入密码");
        return
      }
    }
    this.setData({
      loading: true
    });

    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: "",
    }
    let bodyInfo = {
      loginType: "password",
      thirdLoginId: app.globalData.openid,
      unionid: app.globalData.unionid,
      mobileNo: telPhone,
      avatar: this.data.avatarUrl,
      nickName: this.data.nickName,
      regChannel:'6',
      password: password
    }
    let _that = this;
    request.requestLogin_api("userLogin", headerInfo, bodyInfo, (res) => {
      wx.hideLoading();
      _that.setData({
        loading: false
      });
      console.log("密码登录=", res)
      
      if (res.data.isSuccess == "F"){
        if (res.data.errorCode == "ILLEGAL_SIGN"){
          _that.showErrorMsg("签到出错");
        }else{
          _that.showErrorMsg(res.data.errorMsg);
        }
        
      }else{
        app.globalData.sessionId = res.data.sessionId;
      //保存手机号
       app.globalData.mobileNo = JSON.parse(res.data.body).mobileNo;
       app.globalData.userName = JSON.parse(res.data.body).userName;
       app.globalData.identity = "";
      //  wx.navigateBack();
        wx.redirectTo({
          url: '../index/index',
        })
      }
    }, (res) => {
      _that.setData({
        loading: false
      });
      console.log("密码登录失败=", res)
    });
  },

  //验证码登录
  yanZcodeFun:function(){
    var VerCode = this.data.VerCode;
    var telPhone = this.data.telPhone;
    if (!telPhone) {
      this.showErrorMsg("请输入手机号");
      return
    } else if (!utilApi.isValidNo(telPhone)) {
      this.showErrorMsg("手机号格式不正确");
      return
    }else if (this.data.hasTel) {
      if (!VerCode) {
        this.showErrorMsg("请输入验证码");
        return
      }
    }
    this.setData({
      loading: true
    });
    if (!this.data.hasTel) {
      VerCode = "SUCCESS";
    }
    let headerInfo = {
      pageNum: "",
      pageSize: "",
      sessionId: "",
    }
    let bodyInfo = {
      loginType: "mp",
      thirdLoginId: app.globalData.openid,
      unionid: app.globalData.unionid,
      mobileNo: this.data.telPhone,
      avatar: this.data.avatarUrl,
      nickName: this.data.nickName,
      regChannel: '6',
      mobileCheckNo: VerCode
    }
    let _that = this;
    request.requestLogin_api("userLogin", headerInfo, bodyInfo, (res) => {
      wx.hideLoading();
      _that.setData({
        loading: false
      });
      console.log("注册成功=", res)
      if (res.data.isSuccess == "F") {
        if (res.data.errorCode == "ILLEGAL_SIGN") {
          _that.showErrorMsg("签到出错ILLEGAL_SIGN");
        } else {
          _that.showErrorMsg(res.data.errorMsg);
        }
      }else{
        app.globalData.sessionId = res.data.sessionId;
        //保存手机号
        app.globalData.mobileNo = JSON.parse(res.data.body).mobileNo;
        app.globalData.userName = JSON.parse(res.data.body).userName;
        app.globalData.identity = "";
        // wx.navigateBack();
        wx.redirectTo({
          url: '../index/index',
        })
      }
      
    }, (res) => {
      _that.setData({
        loading: false
      });
      console.log("注册失败=", res)
    });
  },

  //获取用户信息
  getUserInfoAgain: function(){
    let _this = this;
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        console.log("获取用户==================",res)
        _this.setData({
          avatarUrl: res.userInfo.avatarUrl,
          nickName: res.userInfo.nickName
        });
      },
      fail: res => {
        console.log("获取用户信息失败=", res)
      }
    })
  },

  //switch触发改变
  // switchChange: function(e){
  //   console.log('switch发生 change 事件，携带值为', e.detail.value)
  //   let msg = this.data.loginTypeMsg;
  //   if (msg== "使用账号密码登录"){
  //     this.setData({
  //       showPwdLogin: true,
  //       loginTypeMsg:"手机号快速登录"
  //     });
  //   }else{
  //     this.setData({
  //       showPwdLogin: false,
  //       loginTypeMsg: "使用账号密码登录"
  //     });
  //   }
    
  // },



  //快速获取手机号权限
  getPhoneNumber: function (e) {
    // console.log(e.detail.errMsg)
    // console.log(e.detail.iv)
    // console.log(e.detail.encryptedData)
    let _that = this;
    console.log("getPhoneNumber=", e)
    if (e.detail.errMsg == 'getPhoneNumber:ok'){
      try{
        let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
        let decodeData = pc.decryptData(e.detail.encryptedData, e.detail.iv);
        console.log('解密后 decodeData: ', decodeData);
        if (!decodeData.purePhoneNumber){
          _that.showErrorMsg("快速获取失败，请验证码登录");
          if (_that.data.telPhone) {
            _that.setData({
              inputYzmLight: false
            })
          }
          _that.setData({
            showPwdLogin: false,//密码
            hasTel: true,//验证码
            showQuickLogin: false//快速登录
          });
          return
        }
        _that.setData({
          telPhone: decodeData.purePhoneNumber,
          isClickOver: true
        });

        _that.yanZcodeFun();
      }catch(e){
        _that.showErrorMsg("快速获取失败，请验证码登录");
        if (_that.data.telPhone) {
          _that.setData({
            inputYzmLight: false
          })
        }
        _that.setData({
          showPwdLogin: false,//密码
          hasTel: true,//验证码
          showQuickLogin: false//快速登录
        });
      }
    }else{
      _that.showErrorMsg("快速获取失败，请验证码登录");
      if (_that.data.telPhone) {
        _that.setData({
          inputYzmLight: false
        })
      }
      _that.setData({
        showPwdLogin: false,//密码
        hasTel: true,//验证码
        showQuickLogin: false//快速登录
      });
    }
    // if (e.detail.errMsg == 'getPhoneNumber:fail user deny' || e.detail.errMsg == 'getPhoneNumber:fail:cancel to confirm login' || e.detail.errMsg == 'getPhoneNumber:fail:access denied') {
    // } 
  },
  //errorMsg显示
  showErrorMsg: function (msg) {
    this.setData({
      errorMsg: msg
    });
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })
    this.animation = animation
    animation.translateY(26).step()
    this.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.translateY(-26).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 2000)
  },
})